<html>
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<head>
<title>Section 12.4.&nbsp; Presenting a Form to Add and Process in One File</title>
<link rel="STYLESHEET" type="text/css" href="images/style.css">
<link rel="STYLESHEET" type="text/css" href="images/docsafari.css">
<script type="text/javascript"><!--
google_ad_client = "pub-0203281046321155";
google_alternate_ad_url = "http://www.bookhtml.com/adbrite.htm";
google_ad_width = 728;
google_ad_height = 90;
google_ad_format = "728x90_as";
google_ad_type = "text_image";
google_ad_channel ="4867465545";
google_color_border = "FFFFFF";
google_color_link = "0000FF";
google_color_bg = "FFFFFF";
google_color_text = "000000";
google_color_url = "0000FF";
//--></script>
<script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-12-SECT-3.html><img src="images/prev.gif" width="60" height="17" border="0" align="absmiddle" alt="Previous Page"></a>
<td align="right"><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-12-SECT-5.html><img src="images/next.gif" width="60" height="17" border="0" align="absmiddle" alt="Next Page"></a>
</div></td></tr></table>
<br><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><TD valign="top"><a name="learnphpmysql-CHP-12-SECT-4"></a>
<h3 id="631450-833" class="docSection1Title">12.4. Presenting a Form to Add and Process in One File</h3>
<a name="IDX-CHP-12-0592"></a> 
<a name="IDX-CHP-12-0593"></a> 

<p class="docText">We're building a form that allows a web user to add a title to the <tt>books</tt> table. <a class="docLink" href="#learnphpmysql-CHP-12-EX-6">Example 12-6</a> is a slightly longer example, because we display and process the form in one file, but it should look familiar to you since we're simply combining several steps that we've done separately before.</p>
<a name="learnphpmysql-CHP-12-EX-6"></a><h5 id="title-IDAQDBWC" class="docExampleTitle">Example 12-6. Using input from a form to add a title</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;?php
<span class="docEmphStrong">// Define a function to perform the database insert and display the titles
function insert_db($title, $pages){</span>
require_once('db_login.php');
require_once('DB.php');
$connection = DB::connect("mysql://$db_username:$db_password@$db_host/$db_database");
if (DB::isError($connection)){
die ("Could not connect to the database: &lt;br /&gt;". DB::errorMessage($connection));
}
// The query includes the form sumbission values that were passed to the function
<span class="docEmphStrong">$query = "INSERT INTO `books` VALUES (NULL,'$title','$pages')";</span>
$result = $connection-&gt;query($query);
if (DB::isError($result)){
die("Could not query the database: &lt;br /&gt;". $query." ".DB::errorMessage($result));
}
<span class="docEmphStrong">echo "Inserted OK.&lt;br /&gt;";</span>
// Display the table
$query = "SELECT * FROM `books`";
$result = $connection-&gt;query($query);
if (DB::isError($result)){
die("Could not query the database: &lt;br /&gt;". $query." ".DB::errorMessage($result));
}
echo '&lt;table border="1"&gt;';
echo "&lt;tr&gt;&lt;th&gt;Title&lt;/th&gt;&lt;th&gt;Pages&lt;/th&gt;&lt;/tr&gt;";
while ($result_row = $result-&gt;fetchRow(DB_FETCHMODE_ASSOC)) {
echo "&lt;tr&gt;&lt;td&gt;";
echo $result_row["title"] . '&lt;/td&gt;&lt;td&gt;';
echo $result_row["pages"] . '&lt;/td&gt;&lt;/tr&gt;';
}
echo "&lt;/table&gt;";
$connection-&gt;disconnect();
}

?&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Inserting From a Form&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;?php
// Retrieve the variable from the form submission
<span class="docEmphStrong">$title = $_GET["title"];
$pages = $_GET["pages"];</span>
if (($title != NULL ) &amp;&amp; ($pages != NULL)){
insert_db($title,$pages);
}
else {
// Display the form
echo '
&lt;h1&gt;Enter a new title:&lt;/h1&gt;
<span class="docEmphStrong">&lt;form action="'.$_SERVER["PHP_SELF"].'" method="GET"&gt;
&lt;label&gt;
Title:
&lt;input type="text" name="title" id="title" /&gt;
&lt;/label&gt;
&lt;label&gt;
Pages:
&lt;input type="text" name="pages" id="pages" /&gt;
&lt;/label&gt;</span>
&lt;input type="submit" value="Go!" /&gt;
&lt;/form&gt;';
}
?&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><br>

</td></tr></table></p>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-12-EX-6">Example 12-6</a> begins by displaying a form like <a class="docLink" href="#learnphpmysql-CHP-12-FIG-6">Figure 12-6</a>, using the code in the body of the file if the <tt>$title</tt> and <tt>$pages</tt> values do not have both values set.</P>
<a name="learnphpmysql-CHP-12-FIG-6"></a><p><center>
<h5 class="docFigureTitle">Figure 12-6. This is how the form looks with some sample data in the field</H5>
<img border="0" alt="" id="195131084199" width="514" height="165" SRC="images/learnphpmysql_1206.jpg">
</center></P><br>
<p class="docText">Once the user enters values into both fields and clicks the <tt>Go!</tt> button, the same script handles the form submission processing. Since values exist for the two fields, the <tt>insert_db</tt> function is called with those values. The values are placed into the query string enclosed by single quotes (' '):</P>
<pre>
$query = "INSERT INTO 'books' VALUES (NULL,'$title','$pages')";
</pre><br>

<p class="docText">This query is then executed like any other query. Finally, the function queries the <tt>books</tt> table and displays the resuss in an HTML table.</p>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-12-FIG-7">Figure 12-7</a> shows what happens after clicking the <tt>Go!</tt> button with the sample data above.</p>
<a name="learnphpmysql-CHP-12-FIG-7"></a><P><center>
<h5 class="docFigureTitle">Figure 12-7. The results page shows the new entry</H5>
<img border="0" alt="" id="195131084199" width="514" height="197" SRC="images/learnphpmysql_1207.jpg">
</center></p><br>
<p class="docText">You must take several precautions when working with strings submitted from a form that will be processed by the database.</P>
<a name="learnphpmysql-CHP-12-SECT-4.1"></a>
<H4 id="title-IDAPGBWC" class="docSection2Title">12.4.1. SQL Injection</h4>
<p class="docText">Specifically, you need to be on guard for a tactic called SQL injection.<a name="IDX-CHP-12-0594"></a> 
<a name="IDX-CHP-12-0595"></a> 
 <span class="docEmphasis">SQL injection</span> is when a malicious user enters another SQL query into a field such as <tt>1,1);drop table users;</tt>. When this query is added to a query like this:</P>
<pre>
$query = "INSERT INTO 'books' VALUES (NULL,$title,$pages)";
</pre><br>

<p class="docText">here's what could happen:</p>
<pre>
$query = "INSERT INTO 'books' VALUES (NULL,1,1);drop table users; ,$pages)";
</pre><BR>

<p class="docText">PHP and MySQL work together to thwart this kind of attack. What happens is the MySQL query command allows only one statement per query. So attempting to start a new query after the first one has already been started generates an error. Additionally, PHP uses a system by default called <span class="docEmphasis">magic quotes</span> with user input. Magic quotes automatically escape any special characters with a backslash (\), including single and double quotes.</P>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-12-EX-7">Example 12-7</a> shows how to test whether magic quotes are enabled on your installation of PHP.</p>
<a name="learnphpmysql-CHP-12-EX-7"></a><h5 id="title-IDAXHBWC" class="docExampleTitle">Example 12-7. Checking for magic quotes</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><TR><td>

<pre>
&lt;?php
if (get_magic_quotes_gpc()) {
echo "Magic quotes are enabled.";
} else {
echo "Magic quotes are disabled.";
}
?&gt;
</pre><BR>

</td></tr></table></P>
<p class="docText">The script should return:</P>
<pre>
Magic quotes are enabled.
</pre><br>

<p class="docText">Because the PEAR DB abstraction layer is being used, MySQL-specific escaping should not be used simultaneously. Use the PEAR <tt>escapeSimple($string)</tt> function to do your escaping with PEAR code.</P>
<p class="docText">If magic quotes are off, you can use the <tt>add_slashes</tt> function to accomplish the same thing with your input. Nonetheless, you should look out for these errors, since other databases may allow more than one statement per query. Be skeptical of user input, or you could end up with a compromised database.</p>

<a name="learnphpmysql-CHP-12-SECT-4.2"></a>
<h4 id="title-IDASIBWC" class="docSection2Title">12.4.2. Cross-Site Scripting Attacks</h4>
<a name="IDX-CHP-12-0596"></a> 
<a name="IDX-CHP-12-0597"></a> 
<a name="IDX-CHP-12-0598"></a> 

<p class="docText">One last gotcha to look out for when using data from user input is the risk of <span class="docEmphasis">cross-site scripting</span> attacks. These attacks work slightly differently than SQL injection. They don't compromise the data on your server, but instead can lead to a user's browser giving out sensitive data to a third party because the browser thinks the command came from your trusted site. To guard against these attacks, you should pass any strings that came from a user through the <tt>htmlentities</tt> function. It takes the format:</p>
<pre>
htmlentities(<tt><i>string_to_clean</i></tt>)
</pre><br>

<p class="docText">For example:</p>
<pre>
print "The title of the book is: " .
htmlentities($_POST['title']);
</pre><br>

<p class="docText">Here's an example of what <tt>htmlentities</tt> does to the string:</p>
<pre>
&lt;?php
$sample = "A sample is &lt;i&gt;italics&lt;/i&gt;";
echo htmlentities($sample);
?&gt;
</pre><br>

<p class="docText">When executed, this returns:</p>
<pre>
A sample is &amp;lt;i&amp;gt;italics&amp;lt;/i&amp;gt;
</pre><BR>

<p class="docText">Essentially, you're guarding against the same problem as SQL injection, but the code that's vulnerable is the HTML. The special function HTML characters such as less than (<tt>&lt;</tt>) and greater than (<tt>&gt;</tt>) are escaped, preventing hostile HTML code from working when displayed from your site.</p>
<p class="docText">Here's a script to display the <tt>title</tt> table with the <tt>htmlentities</tt> functionality added:</p>
<pre>
&lt;?php
require_once('db_login.php');
require_once('DB.php');
$connection = DB::connect("mysql://$db_username:$db_password@$db_host/$db_database");
if (DB::isError($connection)){
die ("Could not connect to the database: &lt;br /&gt;". DB::errorMessage($connection));
}
// Dislplay the table
$query = "SELECT * FROM `books`";
$result = $connection-&gt;query($query);
if (DB::isError($result)){
die("Could not query the database: &lt;br /&gt;".$query." ".DB::errorMessage($result));
}
echo '&lt;table border="1"&gt;';
echo "&lt;tr&gt;&lt;th&gt;Title&lt;/th&gt;&lt;th&gt;Pages&lt;/th&gt;&lt;/tr&gt;";
while ($result_row = $result-&gt;fetchRow(DB_FETCHMODE_ASSOC)) {
echo "&lt;tr&gt;&lt;td&gt;";
echo htmlentities($result_row["title"]) . '&lt;/td&gt;&lt;td&gt;';
echo htmlentities($result_row["pages"]) . '&lt;/td&gt;&lt;/tr&gt;';
}
echo "&lt;/table&gt;";
$connection-&gt;disconnect();
?&gt;
</pre><BR>

<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-12-FIG-8">Figure 12-8</a> shows that <tt>htmlentities</tt> didn't change the look of your table.</P>
<a name="learnphpmysql-CHP-12-FIG-8"></a><p><center>
<H5 class="docFigureTitle">Figure 12-8. No change is made to the look of your table</h5>
<img border="0" alt="" id="195131084199" width="463" height="185" SRC="images/learnphpmysql_1208.jpg">
</center></p><br>
<p class="docText">You can be assured that you've prevented any malicious HTML that may have been entered by a user from confusing another user's browser.</P>


</TD></TR></table>
<br>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-12-SECT-3.html><img src="images/prev.gif" width="60" height="17" border="0" align="absmiddle" alt="Previous Page"></a>
<td align="right"><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-12-SECT-5.html><img src="images/next.gif" width="60" height="17" border="0" align="absmiddle" alt="Next Page"></a>
</div></td></tr></table>
</body></html>
